function groupTab(tabId, matchingGroup) {
  if (chrome.tabGroups) {
    chrome.tabGroups.query({title: matchingGroup.groupName}, (groups) => {
      if (groups.length > 0) {
        chrome.tabs.group({tabIds: tabId, groupId: groups[0].id});
      } else {
        chrome.tabs.group({tabIds: tabId}, (groupId) => {
          chrome.tabGroups.update(groupId, {
            title: matchingGroup.groupName,
            color: matchingGroup.color
          });
        });
      }
    });
  } else {
    console.log("tabGroups API不可用,使用替代方法");
    // 这里可以添加一些替代逻辑,例如使用标签页标题来模拟分组
    chrome.tabs.get(tabId, (tab) => {
      chrome.tabs.update(tabId, {title: `[${matchingGroup.groupName}] ${tab.title}`});
    });
  }
}

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status === 'complete') {
    chrome.storage.sync.get('tabGroups', function(data) {
      const tabGroups = data.tabGroups || [];
      const url = new URL(tab.url);
      const matchingGroup = tabGroups.find(group => url.hostname.includes(group.domain));

      if (matchingGroup) {
        groupTab(tabId, matchingGroup);
      }
    });
  }
});